package com.briup.bms.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.briup.bms.bean.Employee;
import com.briup.bms.common.exceptions.BmsServiceException;
import com.briup.bms.common.utils.EmpInfoHolder;
import com.briup.bms.common.utils.JWTUtils;
import com.briup.bms.common.utils.ResultCode;
import com.briup.bms.dao.IEmpMapper;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;

@Component
public class AuthInterceptor implements HandlerInterceptor {
	@Autowired
	private IEmpMapper empMapper;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//判断请求头中是否携带了token，只有携带了token才有可能是已经认证通过的用户
		if("OPTIONS".equals(request.getMethod())) {
			return true;
		}
		String token = request.getHeader("token");
		if(token==null||"".equals(token.trim())) {	//如果没有携带，代表非认证用户，请先登录。
			throw new BmsServiceException(ResultCode.USER_NOT_LOGIN, "请先登录！");
		}
		try {
			//String name = JWTUtils.getUsername(token);	//token解析，如果没有异常，继续向下执行。
			String userId = JWTUtils.getUserId(token); //解析令牌。
			Employee emp = empMapper.findUserId(userId);
			if(emp==null) {
				throw new BmsServiceException(ResultCode.USER_NOT_LOGIN, "非法的令牌，请重新登录！");
			}
			EmpInfoHolder.setEmp(emp);
		}catch (ExpiredJwtException e) {
			throw new BmsServiceException(ResultCode.USER_NOT_LOGIN, "token过期！请重新登录！");
		}catch (SignatureException|MalformedJwtException e) {
			throw new BmsServiceException(ResultCode.USER_NOT_LOGIN, "非法token！请先正常登陆！");
		}
		//在添加逻辑，进行权限拦截。
		//根据请求的url=====当前登录用户的title，进行匹配。
		
		return true;
	}
}
